package com.mpc.params;

import com.mpc.adapter.LanguagesAdapter;
import com.mpc.utils.*;

public class MainTabPageParams {
    private static final String TAG = MainTabPageParams.class.getSimpleName();

    public static final int INDEX_LANGUAGES = 0;

    public static final String KEY_LANGUAGES = "lan";
    public static final String LANGUAGES_ZH = LanguagesAdapter.LAN_ZH;
    public static final String LANGUAGES_EN = LanguagesAdapter.LAN_EN;

    private String languages = null;

    public MainTabPageParams() {
    }

    public boolean isSetLanguages() {
        if (languages == null) {
            return false;
        } else {
            return true;
        }
    }

    public String getLanguages() {
        return languages;
    }

    public void setLanguages(String languages) {
        this.languages = languages;
    }

    public String toQueryString(boolean rewritten) {
        String query = null;
        if (!rewritten) {
            if (isSetLanguages()) {
                query = KEY_LANGUAGES + "=" + languages;
            }
        } else {
            if (isSetLanguages()) {
                query = languages;
            }
        }

        return query;
    }

    // normal : lan=en&data=xxx
    // rewrite : en_xxx
    public static MainTabPageParams parse(String query, boolean isRewritten) {
        if (query == null || query.length() == 0) {
            Log.d(TAG, "query is empty !");
            return null;
        }

        MainTabPageParams params = new MainTabPageParams();
        boolean isValid = true;
        if (!isRewritten) {
            String[] kvsArray = query.split("&");

            for (int i = 0; i < kvsArray.length; i++) {
                String[] kvArray = kvsArray[i].split("=");
                if (!setParams(params, i, kvArray)) {
                    isValid = false;
                }

                if (!isValid) {
                    Log.d(TAG, "query "+ query +" is invalidate !");
                    return null;
                }
            }

        } else {
            String[] values = query.split("_");
            for (int i = 0; i < values.length; i++) {
                switch (i) {
                case INDEX_LANGUAGES:
                    params.setLanguages(values[i]);
                    break;
                }
            }
        }

        return params;
    }

    private static boolean setParams(MainTabPageParams params, int fieldIndex,
            String[] kvArray) {
        switch (fieldIndex) {
        case INDEX_LANGUAGES:
            if (KEY_LANGUAGES.equals(kvArray[0])) {
                params.setLanguages(kvArray[1]);
                return true;
            } else {
                Log.d(TAG, "Feild " + KEY_LANGUAGES + " is expected !");
                return false;
            }
        }
        Log.d(TAG, "FeildIndex " + fieldIndex + " is not exist !");
        return false;
    }
}
